﻿using System;
using System.Collections.Concurrent;
using System.ComponentModel;

namespace Core
{
    /// <summary>
    /// WPF数据绑定实体基类
    /// </summary>
    public class WPFBindingEntity : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 属性处理拦截器
        /// </summary>
        private readonly ConcurrentDictionary<string, Callback> handlers = new ConcurrentDictionary<string, Callback>();

        /// <summary>
        /// 通知属性更改
        /// </summary>
        /// <param name="propertyName"></param>
        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            if(handlers.TryGetValue(propertyName, out Callback callback))
            {
                callback?.Invoke();
            }
        }

        public void InterceptChanged(string name, Callback callback)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("property name must not be null.");

            if(!handlers.TryAdd(name, callback))
            {
                handlers[name] = callback;
            }
        }
    }
}
